var Basicdata = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();
    var checkName_url = $('.checkName_url').val();

    var dataArr = [];

    // 作物品种
    var cropDataTemp = stringLines(function(){/*
	<tr >
		<td>
            <div class="">
                <div id="upload-image">
                    <span id="upload-btn" data-multi="false">
                        <div class="exist-img" style="width: 100%;">
                            <input type="hidden" class="form-control" data-required="1" name="imgUrl" value="">
                            <img src="/public/static/admin/img/default.png" alt="图片上传" style="width: 200px;height: 100px;" />
                        </div>
                    </span>
                </div>
                <span class="help-block"> (建议尺寸：220*220) </span>
            </div>
	    </td>
	    <td>
            <input type="text" class="form-control" id="name" name="name" data-name="" value="">
	    </td>
	    <td>
	        <input type="hidden" class="parentId" name="parentId" value="0">
	        <input type="hidden" class="id" name="id" value="">
            <input type="hidden" class="type" name="type" value="">
            <input type="hidden" class="ori_name" name="ori_name" value="">
            <input type="hidden" class="level" name="level" value="0">

            <button type="button" class="btn blue save-btn">保存</button>
            <button type="button" class="btn default cancel-btn">取消</button>
	    </td>
	</tr>
*/});
    // 基础数据
    var dataTemp = stringLines(function(){/*
	<tr >
	    <td>
            <input type="text" class="form-control" id="name" name="name" data-name="" value="">
	    </td>
	    <td>
	        <input type="hidden" class="id" name="id" value="">
            <input type="hidden" class="type" name="type" value="">
            <input type="hidden" class="ori_name" name="ori_name" value="">

            <button type="button" class="btn blue save-btn">保存</button>
            <button type="button" class="btn default cancel-btn">取消</button>
	    </td>
	</tr>
*/});


    // 作物品种
    var initCropTable = function(type) {
        dataArr.push(type);
        var table = $('#'+type+'-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                "paging": false, // 禁止分页
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                    data: {'type': type}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            if (!data) {
                                data = '/public/static/admin/img/default.png';
                            }

                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 40px;height: 40px;"/></a>';
                        }
                    },
                    {
                        "data": "name",
                        "render": function(data, type, row, meta) {
                            var space = '';
                            for (var i = 0; i < row.level; i++) {
                                space += '&nbsp;├&nbsp;';
                            }

                            return space + data;
                        }
                    },
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            if(ADMININFO.type == 0 || row.createOper == ADMININFO.id){
                                if (row.level <= 1) {
                                    // 最多3级
                                    html += '<button type="button" class="btn btn-info addChild-btn">添加子级</button>';
                                }
                                html += '<button type="button" class="btn btn-success edit-btn">编辑</button>';
                                html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            }

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "createdRow": function(row, data, dataIndex) {
                    $(row).children('td').eq(1).css({'text-align': 'left', 'padding-left':'10px'});
                    $(row).children('td').eq(2).css({'text-align': 'right', 'padding-right':'10px'});
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 新增或保存
        table.on('click', '.save-btn', function(event) {
            var imgUrl = $('.tab-content').find('table').find('[name="imgUrl"]').val();
            var name = $('.tab-content').find('table').find('[name="name"]').val();
            var ori_name = $('.tab-content').find('table').find('[name="ori_name"]').val();
            var parentId = $('.tab-content').find('table').find('[name="parentId"]').val();
            var level = $('.tab-content').find('table').find('[name="level"]').val();
            var type = $('.nav-tabs').find('li.active a').data('type');
            var _id = $('.tab-content').find('table').find('[name="id"]').val();

            /*if (!mdTool.validate(imgUrl, 'require')) {
                layer.msg('请上传图片');
                return;
            }*/
            if (!mdTool.validate(name, 'require')) {
                layer.msg('请输入名称');
                return;
            }
            if(name.length > 30){
                layer.msg('名称最多为30个字符');
                return false;
            }

            var param = {
                'id': _id,
                'imgUrl': imgUrl,
                'name': name,
                'ori_name': ori_name,
                'parentId': parentId,
                'level': level,
                'type': type,
            };

            $.ajax({
                url : save_url,
                type : 'post',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(param),
            }).done(function(data) {
                if (data.code == 1) {
                    $(document).find('.add-btn').prop('disabled', false);
                    table.DataTable().ajax.reload();
                    //table.DataTable().draw(false);
                } else {
                    layer.msg(data.msg);
                }
            });
            return false;
        });

        // 修改
        table.on('click', '.edit-btn', function(event) {
            $(this).prop('disabled', true);
            $(this).parent().find('.addChild-btn').prop('disabled', true);
            $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
            $(this).parents("tr").siblings("tr").find(".addChild-btn").prop('disabled', true);
            $(document).find('.add-btn').prop('disabled', true);

            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var imgUrl = dataArr[0].imgUrl;
            if (!imgUrl) {
                imgUrl = '/public/static/admin/img/default.png';
            }
            var name = dataArr[0].name;
            var type = $('.nav-tabs').find('li.active a').data('type');

            table.find("tbody:last").append(cropDataTemp);
            table.find('[name="imgUrl"]').val(imgUrl);
            table.find('.exist-img').find('img').attr('src', imgUrl);
            table.find("[name='name']").val(name);
            table.find("[name='ori_name']").val(name);
            table.find("[name='type']").val(type);
            table.find('input[name="id"]').val(id);
            initUploader();
        });

        // 添加子级
        table.on('click', '.addChild-btn', function(event) {
            $(this).prop('disabled', true);
            $(this).parent().find('.edit-btn').prop('disabled', true);
            $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
            $(this).parents("tr").siblings("tr").find(".addChild-btn").prop('disabled', true);
            $(document).find('.add-btn').prop('disabled', true);

            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var level = dataArr[0].level;
            var type = $('.nav-tabs').find('li.active a').data('type');

            table.find("tbody:last").append(cropDataTemp);
            table.find("[name='type']").val(type);
            table.find('input[name="parentId"]').val(id);
            table.find('input[name="level"]').val(level + 1);
            initUploader();
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id, 'type':'crop'};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    // 基础数据
    var initTable = function(type) {
        dataArr.push(type);
        var table = $('#'+type+'-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                    data: {'type': type}
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            if(ADMININFO.type == 0 || row.createOper == ADMININFO.id){
                                html += '<button type="button" class="btn btn-success edit-btn">编辑</button>';
                                html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            }

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 新增或保存
        table.on('click', '.save-btn', function(event) {
            var name = $('.tab-content').find('table').find('[name="name"]').val();
            var ori_name = $('.tab-content').find('table').find('[name="ori_name"]').val();
            var type = $('.nav-tabs').find('li.active a').data('type');
            var _id = $('.tab-content').find('table').find('[name="id"]').val();

            if (!mdTool.validate(name, 'require')) {
                layer.msg('请输入名称');
                return;
            }
            if(name.length > 30){
                layer.msg('名称最多为30个字符');
                return false;
            }

            var param = {
                'id': _id,
                'name': name,
                'ori_name': ori_name,
                'type': type,
            };

            $.ajax({
                url : save_url,
                type : 'post',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(param),
            }).done(function(data) {
                if (data.code == 1) {
                    $(document).find('.add-btn').prop('disabled', false);
                    table.DataTable().ajax.reload();
                    //table.DataTable().draw(false);
                } else {
                    layer.msg(data.msg);
                }
            });
            return false;
        });

        // 修改
        table.on('click', '.edit-btn', function(event) {
            $(this).prop('disabled', true);
            $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
            $(document).find('.add-btn').prop('disabled', true);

            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var name = dataArr[0].name;
            var type = $('.nav-tabs').find('li.active a').data('type');

            table.find("tbody:last").append(dataTemp);
            table.find("[name='name']").val(name);
            table.find("[name='ori_name']").val(name);
            table.find("[name='type']").val(type);
            table.find('input[name="id"]').val(id);
            initUploader();
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    //++ 七牛上传初始化 Begin ++//
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = '1MB';
    var extensions = 'jpg,jpeg,gif,png';
    var multi = false;
    var initUploader = function () {
        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                var url = "";
                var qiniupercent = "";

                if($('#upload-image').length > 0){
                    uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image', 'upload-btn', max_file_size, extensions, multi);
                }
            }
        });
    };
    var uploaderImgReady = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            // container: uploader,      //上传按钮的上级元素ID
            // drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                // 删除原图
                                var img_id = $('#' + pickfiles).find('input[name=imgId]').val();
                                var img_url = $('#' + pickfiles).find('img').attr('src');
                                delOriginalImg(img_id, img_url);

                                if($('#' + pickfiles).find('.exist-img').length > 0) {
                                    $('#' + pickfiles).find('img').attr('src', sourceLink);
                                    $('#' + pickfiles).find('input[name=imgUrl]').val(sourceLink);
                                    $('#' + pickfiles).find('input[name=imgId]').val(data.image_id);
                                } else {
                                    var html = '';
                                    html += '<div class="exist-img">';
                                    html += '<input type="hidden" class="form-control" name="imgUrl" value="'+sourceLink+'">';
                                    html += '<img src="'+sourceLink+'" alt="图片上传" />';
                                    html += '</div>';

                                    $('#' + pickfiles).find('.uploader-div').hide();
                                    $('#' + pickfiles).append(html);
                                    $('#' + pickfiles).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };
    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };
    //++ 七牛上传初始化 End ++//

    // 表单提交
    /*var submitForm = function(btnObj) {
        var form = document.getElementById("ajax-form");
        var _this = btnObj;

        /!*if(form.imgUrl.value.trim() == ''){
            layer.msg('请上传图片');
            return false;
        }*!/

        var _data = $(form).serializeObject();
        _this.prop("disabled", true);
        $.ajax({
            url : save_url,
            type : 'post',
            dataType : 'json',
            contentType : "application/json; charset=utf-8",
            data : JSON.stringify(_data),
        }).done(function(data) {
            if (data.code == 1) {
                layer.msg('保存成功');
                window.location.href = data.url;
            } else {
                _this.prop("disabled", false);
                layer.msg(data.msg);
            }
        });
    };*/


    return {
        init: function() {
            initCropTable('crop');

            this.onEvent();
        },

        onEvent : function(){

            // Tab 切换
            $('.data-tab').on('click', function(){
                var type = $(this).data('type');
                //console.log($.inArray(type, dataArr));
                $(document).find('.add-btn').prop('disabled', false);
                if ($.inArray(type, dataArr) < 0) {
                    /*if (type == 'crop') {
                        initCropTable(type);
                    } else {
                        initTable(type);
                    }*/
                    initTable(type);
                } else {
                    var table = $('#'+type+'-table');
                    table.DataTable().ajax.reload();
                }
            });


            // 添加
            $('.add-btn').on('click', function(){
                $(this).prop('disabled', true);
                var type = $('.nav-tabs').find('li.active a').data('type');
                var table = $('#'+type+'-table');
                $('.tab-content').find('table .edit-btn').prop('disabled', true);
                $('.tab-content').find('table .addChild-btn').prop('disabled', true);
                if (type == 'crop') {
                    table.find('tbody:last').append(cropDataTemp);
                } else {
                    table.find('tbody:last').append(dataTemp);
                }

                table.find("[name='type']").val(type);

                //$('#view-modal').modal('show');
                //$('#view-modal').find('input[name=type]').val(type);

                initUploader();
            });

            // 取消按钮 （通用）
            $(document).on('click', '.cancel-btn',function(){
                $(this).parents('table').find('.edit-btn').prop('disabled', false);
                $(this).parents('table').find('.addChild-btn').prop('disabled', false);
                $(document).find('.add-btn').prop('disabled', false);
                $(this).parents('tr').remove();
                return false;
            });

            // 保存
            /*$('.save-btn').on('click', function(){
                var form = document.getElementById("ajax-form");
                var _this = $(this);
                var type = $('.nav-tabs').find('li.active a').data('type');

                if(form.name.value.trim()=='') {
                    layer.msg('请输入名称');
                    form.name.focus();
                    return;
                }
                if(form.name.value.length > 30){
                    layer.msg('名称最多为30个字符');
                    form.name.focus();
                    return false;
                }

                var name = $('#name').val();
                var ori_name = $('#name').attr('data-name');

                if(name != ori_name){
                    var url = checkName_url;
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: {'name': name, 'type': type},
                        dataType : 'json',
                        success: function (data) {
                            if(data.status == 1){
                                layer.msg('该名称已经存在！');
                                $('#name').focus();
                                return false;
                            }else{
                                submitForm(_this);
                            }
                        }
                    });
                    return false;
                }

                submitForm(_this);
            });*/
        }
    };

}();

$(function() {
    Basicdata.init();
});
